<?php
/**
 * Created by PhpStorm.
 * User: user
 * Date: 2017/3/13
 * Time: 20:53
 */
namespace haibao\jiepai\data;

class Picture extends \haibao\jiepai\data\BaseMysql
{

    public function __construct()
    {
        parent::__construct('\haibao\jiepai\model\data\user\CmsUserAlbums');
    }

    public function getPicture($pictureId)
    {
        $picture = $this->mergeOneDataAndImage(array(), $pictureId);
        return $picture ? array(
            'FileID' => $pictureId,
            'Picture' => $picture['Picture'],
            'FileWidth' => $picture['FileWidth'],
            'FileHeight' => $picture['FileHeight']
        ) : array();
    }

    public function pushPraiseMsg($pictureId, $type = 9, $fromUserId, $toUserId)
    {
        $this->query('insert into cms_messages_praise(ToUserID,FromUserID,TypeID,`Type`,CreateTime) values(%s,%s,%s,%s,%s)', array(
            $toUserId, $fromUserId, $pictureId, $type, date('Y-m-d H:i:s')
        ));
    }

    /**
     * 根据图片ID查询图片详细信息
     */
    public function getPictureById($pictureId)
    {
        return \haibao\cms\business\ImageLibrary::getImageById($pictureId);
    }

    /**
     * 用户行为记录
     */
    public function insertUserAction($userId, $typeId, $type)
    {
        $sql = 'INSERT INTO cms_user_action (Type,TypeID,UserID) select ';
        $sql .= $type . ',' . $typeId;
        $sql .= ',' . $userId . ' from DUAL WHERE NOT EXISTS(SELECT * from cms_user_action where TypeID=' . $typeId;
        $sql .= ' AND Type=' . $type . ' AND Flag = 0 AND UserID = ' . $userId . ')';
        return $this->query($sql);
    }

    /**
     * 取消用户行为记录
     */
    public function updateUserAction($userId, $typeIds, $type)
    {
        $sql = 'UPDATE cms_user_action SET Flag = -1 WHERE Flag = 0 AND TypeID IN (' . $typeIds . ') AND UserID = ' . $userId . ' AND Type=' . $type;
        return $this->query($sql)->getAffectRow();
    }

    /**
     * 根据图片ID列表查询是否被收藏
     */
    public function getIsCollect($userId, array $ids)
    {
        if (!$userId) {
            return array_combine($ids, array_pad(array(), count($ids), 0));
        }

        $existList = array();
        $str = preg_replace('/(\d+)/', '%s', implode(',', $ids));
        $result = $this->query('select distinct(FileID),count(*) as count from cms_album_pictures where UserID=' . intval($userId) . ' and FileID in (' . $str . ') and Flag=0  group by FileID', $ids);
        if ($result) {
            while ($result->fetch_assoc()) {
                array_push($existList, $result->getData('FileID'));
            }
        }
        $collectResult = array();
        foreach ($ids as $key => $imageId) {
            $collectResult[$imageId] = in_array($imageId, $existList) ? 1 : 0;
        }
        return $collectResult;
    }

    /**
     * 根据图片ID列表查询是否被点赞
     */
    public function getIsPraise($userId, array $ids)
    {
        if (!$userId) {
            return array_combine($ids, array_pad(array(), count($ids), 0));
        }

        $existList = array();
        $str = preg_replace('/(\d+)/', '%s', implode(',', $ids));
        $type = \haibao\jiepai\model\data\user\CmsUserAction::TYPE_PICTURE_PRAISE;
        $result = $this->query('select distinct(TypeID) as FileID,count(*) as count from cms_user_action where TypeID in (' . $str . ') and Type=' . $type . ' and Flag=0 group by TypeID', $ids);
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                array_push($existList, $result->getData('FileID'));
            }
        }
        $praiseResult = array();
        foreach ($ids as $key => $imageId) {
            $praiseResult[$imageId] = in_array($imageId, $existList) ? 1 : 0;
        }
        return $praiseResult;
    }

    /**
     * 根据图片ID列表查询图片收藏来源
     */
    public function getCollectSource($ids)
    {
        $sourceResult = array();
        $str = preg_replace('/(\d+)/', '%s', implode(',', $ids));
        $result = $this->query('select distinct(FileID),b.Type,b.Title,b.SubtitleType,b.Subtitle from cms_album_pictures as a left join cms_articles as b on a.ArticleID=b.ArticleID where a.ArticleID!=1 and a.ArticleID is not null and FileID in (' . $str . ') group by a.FileID', $ids);
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                if($row['Type'] == 100 || $row['Type'] == 4){
                    $SubtitleType = $result->getData('SubtitleType');
                    $title = !empty($SubtitleType) ? $SubtitleType : $result->getData('Title');
                }else{
                    $title = $result->getData('Title');
                }
                $sourceResult[$result->getData('FileID')] = $title;
            }
        }
        return $sourceResult;
    }
    /**
     * 查询图片收藏来源(包括人物和文章)
     * SourceType （收藏来源类型 1文章或私照2） TypeID （文章ID或人物ID）
     */
    public function getCollectSourceById($ids){
        $sourceResult = array();
        $str = preg_replace('/(\d+)/', '%s', implode(',', $ids));
        $sql = 'SELECT distinct(FileID),a.ArticleID,b.Type,b.Title,b.SubtitleType,b.Subtitle,c.CelebrityID 
            from cms_album_pictures as a 
            left join cms_articles as b on a.ArticleID=b.ArticleID 
            left join cms_article_celebrity as c on a.ArticleID=c.ArticleID and b.Type=4
            where a.ArticleID!=1 and a.ArticleID is not null and FileID in (' . $str . ') group by a.FileID';
        $result = $this->query($sql,$ids);
        while ($row = $result->fetch_assoc()) {
        	$sourceResult[$result->getData('FileID')]['SourceType'] = (int)$row['Type'];
        	if($row['Type'] == 4){
                $sourceResult[$result->getData('FileID')]['SourceTypeID'] = $result->getData('CelebrityID');
            }else{
                $sourceResult[$result->getData('FileID')]['SourceTypeID'] = $result->getData('ArticleID');
            }
        }
        return $sourceResult;
    }
    
    public function getComments($pictureId, $commentId, $orderType = 1, $prevCursor = null, $nextCursor = null)
    {
        $commentId = ($commentId == 0) ? ($commentId = null) : $commentId;
        if ($orderType == 2) {  // 积分排序
            $rownoSql = 'SELECT rowno FROM (SELECT CommentID,(@rowno:=@rowno+1) as rowno FROM cms_comment ,(SELECT (@rowno:=0)) b WHERE TypeID = ' . $pictureId;
            $rownoSql .= ' AND Type = 2  AND Flag=0 AND AuditStatus!=2 ORDER BY Scores DESC,CreateTime DESC) c ';
            $rownoSql .= 'WHERE c.CommentID = ';

            $commonSql = 'SELECT CommentID,Scores,Content,UserID,CreateTime,SensitiveWords,NickName,rowno,AuditStatus FROM';
            $commonSql .= ' (SELECT t1.CommentID,t1.Scores,t1.Content,t1.UserID,t1.CreateTime,t1.SensitiveWords,t2.NickName,(@rowno:=@rowno+1) as rowno,t1.AuditStatus ';
            $commonSql .= ' FROM cms_comment t1 LEFT JOIN cms_users t2 on t1.UserID = t2.UserID,(SELECT (@rowno:=0)) c';
            $commonSql .= ' WHERE t1.TypeID = ' . $pictureId;
            $commonSql .= ' AND t1.Type = 2 AND t1.Flag = 0 AND t1.AuditStatus != 2 ORDER BY Scores DESC,CreateTime DESC ) d ';

            $sql1 = $sql2 = '';
            if ($commentId) {
                $sql2 = $rownoSql . $commentId;
            } elseif ($nextCursor) {
                $sql2 = $rownoSql . $nextCursor;
            } elseif ($prevCursor) {
                $sql2 = $rownoSql . $prevCursor;
            }
            if ($sql2) {
                $commentArray = array();
                $rowNoArr = $this->query($sql2 . ' limit 1')->fetch_assoc();
                if (!$rowNoArr) {
                    return array('results' => array());
                } else {
                    $index = intval($rowNoArr['rowno']);
                    if ($commentId) {
                        $commonSql . 'where rowno>' . $index . ' and rowno<' . ($index + 16);
                        $commonSql . ' where rowno <= ' . $index . ' ORDER BY rowno DESC LIMIT 16';
                        $result1 = $this->query($commonSql . 'where rowno>' . $index . ' and rowno<' . ($index + 16));
                        $result2 = $this->query($commonSql . ' where rowno <= ' . $index . ' ORDER BY rowno DESC LIMIT 16');
                        $ret1 = array();
                        while ($row1 = $result1->fetch_assoc()) {
                            array_push($ret1, $row1);
                        }
                        $ret2 = array();
                        while ($row = $result2->fetch_assoc()) {
                            array_push($ret2, $row);
                        }
                        $ret2 = $this->arraySort($ret2, 'rowno', SORT_ASC);
                        if (count($ret2) > 15) {
                            $ret2 = array_splice($ret2, 1, 16);
                        }
                        array_push($commentArray, $ret1);
                        array_push($commentArray, $ret2);
                        return $this->getCommentType1($commentArray, $orderType);
                    } else {
                        if ($nextCursor) {
                            $sql = $commonSql . ' WHERE rowno > ' . $index . ' LIMIT ' + (\haibao\classlibrary\Config::getConfig(\haibao\classlibrary\jiepai\Config::COMMENTS_PAGE_SIZE) + 1);
                        } elseif ($prevCursor) {
                            $sql = $commonSql . ' WHERE rowno BETWEEN ' . ($index - \haibao\classlibrary\Config::getConfig(\haibao\classlibrary\jiepai\Config::COMMENTS_PAGE_SIZE) + 1);
                        }
                        $result = $this->query($sql);
                        $commentArray = array();
                        while ($row = $result->fetch_assoc()) {
                            array_push($commentArray, $row);
                        }
                        return $this->getCommentType2($commentArray, $prevCursor, $nextCursor);
                    }
                }
            } else {
                $result = $this->query($commonSql . ' WHERE rowno > 0 LIMIT ' . (\haibao\classlibrary\Config::getConfig(\haibao\classlibrary\jiepai\Config::COMMENTS_PAGE_SIZE) + 1));
                $commentArray = array();
                while ($row = $result->fetch_assoc()) {
                    array_push($commentArray, $row);
                }
                return $this->getCommentType2($commentArray, $prevCursor, $nextCursor);
            }
        } else {
            $commentArray = array();
            $commonSql = 'SELECT t1.CommentID,t1.Scores,t1.Content,t1.SensitiveWords,t1.UserID,t1.CreateTime,t2.NickName,t1.AuditStatus FROM cms_comment t1 ';
            $commonSql .= 'LEFT JOIN cms_users t2 on t1.UserID = t2.UserID ';
            $commonSql .= 'WHERE t1.TypeID=' . $pictureId . ' AND t1.Type = 2 AND t1.Flag = 0 AND t1.AuditStatus != 2';
            if ($commentId) {
                $sql = $commonSql . ' AND t1.CommentID >= ' . $commentId . ' ORDER BY t1.CommentID ASC LIMIT 16';
                $sql1 = $commonSql . ' AND t1.CommentID < ' . $commentId . ' ORDER BY t1.CommentID DESC LIMIT 16';
                $result1 = $this->query($sql);
                $result2 = $this->query($sql1);
                $ret1 = array();
                while ($row = $result1->fetch_assoc()) {
                    array_push($ret1, $row);
                }
                $ret2 = array();
                while ($row = $result2->fetch_assoc()) {
                    array_push($ret2, $row);
                }
                array_push($commentArray, $ret1);
                array_push($commentArray, $ret2);
                return $this->getCommentType1($commentArray, $orderType);
            } else {
                $sql = $commonSql;
                if ($nextCursor) {
                    $sql = $commonSql . ' AND t1.CommentID < ' . $nextCursor;
                } elseif ($prevCursor) {
                    $sql = $commonSql . ' AND t1.CommentID > ' . $prevCursor;
                }
                $sql .= ' ORDER BY t1.CommentID DESC LIMIT ' . (\haibao\classlibrary\Config::getConfig(\haibao\classlibrary\jiepai\Config::COMMENTS_PAGE_SIZE) + 1);
                $result = $this->query($sql);
                while ($row = $result->fetch_assoc()) {
                    array_push($commentArray, $row);
                }
                return $this->getCommentType2($commentArray, $prevCursor, $nextCursor);
            }
        }
    }

    /**
     * 获取评论回复
     */
    public function getReplyComment($commentIds)
    {
        if (!$commentIds) {
            return array();
        }
        $str = preg_replace('/(\d+)/', '%s', implode(',', $commentIds));
        $sql = 'SELECT t1.ReplyID, t1.RepliedID,t1.UserID,t2.NickName,t1.Content,t1.CommentID,t1.SensitiveWords,t1.RepliedUserID,t4.NickName as NickName2,t1.AuditStatus FROM cms_comment_reply t1';
        $sql .= ' LEFT JOIN cms_users t2 on t1.UserID = t2.UserID LEFT JOIN cms_users t4 on t1.RepliedUserID = t4.UserID ';
        $sql .= ' WHERE t1.Flag = 0 AND t1.AuditStatus != 2 AND t1.CommentID in (' . $str . ')';

        $result = $this->query($sql, $commentIds);
        $replyArray = array();
        $replyIds = array();
        while ($row = $result->fetch_assoc()) {
            array_push($replyIds, $row['ReplyID']);
            $temp = array(
                'ReplyID' => $row['ReplyID'],
                'Type' => $row['RepliedID'] ? 2 : 1,
                'ReplyContent' => $row['Content'],
                'AuditStatus' => $row['AuditStatus'],
                'SensitiveWords' => $row['SensitiveWords'],
                'User' => array(
                    'UserID' => $row['UserID'],
                    'NickName' => $row['NickName'],
                    'Avatar' => '',
                ),
                'RepliedUser' => array()
            );
            if ($row['RepliedUserID'] && $row['NickName2']) {
                $temp['RepliedUser'] = array(
                    'UserID' => $row['RepliedUserID'],
                    'NickName' => $row['NickName2'],
                );
            }
            $replyArray[$row['CommentID']][] = $temp;
        }
        $replyPicture = array();
        if ($replyIds) {
            // 取回复的回复的图片
            $replyPicture = $this->getCommentPictures($replyIds, 2);
        }
        if ($replyArray && $replyPicture) {
            // 回复的回复的图片赋值到回复的回复值中
            foreach ($replyArray as $key => $replyList) {
                $replyTmpList = array();
                foreach ($replyList as $k => $reply) {
                    $replyArray[$key][$k]['Pictures'] = isset($replyPicture[$reply['ReplyID']]) ? $replyPicture[$reply['ReplyID']] : array();
                }
            }
        }
        return $replyArray;
    }

    /**
     * 查询评论或评论回复图片，type 1.回复，2.回复的回复
     * @param $replyIds
     * @param $type
     * @return array
     */
    public function getCommentPictures($replyIds, $type)
    {
        if (!$replyIds) {
            return array();
        }
        $str = preg_replace('/(\d+)/', '%s', implode(',', $replyIds));
        $sql = 'SELECT t1.TypeId as ReplyId,t1.PictureID FROM `cms_comment_pictures` t1 WHERE t1.Type = ' . $type . ' AND t1.TypeID in (' . $str . ') and find_in_set(t1.TypeID, "' . implode(',', $replyIds) . '") order by t1.Index ';
        $result = $this->query($sql, array_merge($replyIds, $replyIds));
        $pictureArray = array();
        while ($row = $result->fetch_assoc()) {
            array_push($pictureArray, $row);
        }
        $pictureList = self::mergeDataAndImage($pictureArray, 'PictureID');
        $retArray = array();
        if ($pictureList) {
            foreach ($pictureList as $key => $item) {
                if (empty($item['Picture'])) continue;
                $replyId = $item['ReplyId'];
                $pictureList[$key]['FileID'] = $item['PictureID'];
                unset($item['PictureID'], $item['ReplyId'], $item['CropX'], $item['CropY'], $item['CropWidth'], $item['CropHeight'], $item['Ratio'], $item['Size'], $item['FileDescription']);
                $retArray[$replyId][] = $item;
                unset($pictureList[$key]);
            }
        }
        return $retArray;
    }

    /**
     * 获取评论统计
     */
    public function hotCommentStatistic($results, $userId)
    {
        $commentIds = array();
        foreach ($results as $key => $item) {
            array_push($commentIds, $item['CommentID']);
        }
        $str = preg_replace('/(\d+)/', '%s', implode(',', $commentIds));
        $praiseResult = $this->query('SELECT count(*) as PraiseNum,TypeID as CommentID FROM cms_user_action WHERE Type = 3 and Flag = 0 AND TypeID in (' . $str . ') group by TypeID', $commentIds);
        $replyNumResult = $this->query('SELECT count(*) as ReplyNum,CommentID From cms_comment_reply WHERE CommentID in (' . $str . ') AND AuditStatus !=2 AND Flag = 0  group by CommentID', $commentIds);
        $praiseArray = array();
        while ($row = $praiseResult->fetch_assoc()) {
            $praiseArray[$row['CommentID']] = $row['PraiseNum'];
        }
        $replyNumArray = array();
        while ($row = $replyNumResult->fetch_assoc()) {
            $replyNumArray[$row['CommentID']] = $row['ReplyNum'];
        }
        foreach ($results as $key => $item) {
            $results[$key]['Statistic'] = array(
                'PraiseNum' => isset($praiseArray[$item['CommentID']]) ? $praiseArray[$item['CommentID']] : 0,
                'ReplyNum' => isset($replyNumArray[$item['CommentID']]) ? $replyNumArray[$item['CommentID']] : 0
            );
        }
        return $results;
    }

    public function getCommentUserActions($commentIds, $userId)
    {
        if ($commentIds && $userId) {
            $str = preg_replace('/(\d+)/', '%s', implode(',', $commentIds));
            $result = $this->query('select ID,TypeID as CommentID from cms_user_action where Flag=0 and (`Type`=3 or `Type`=5) and TypeID in (' . $str . ') and UserID=' . $userId, $commentIds);
            $retArr = array();
            while ($row = $result->fetch_assoc()) {
                $retArr[$result->getData('CommentID')] = $row;
            }
            return $retArr;
        } else {
            return false;
        }
    }

    /**
     * 获取回复评论点赞数
     * @param $replyIds
     * @return array
     */
    public function getCommentReplyStatistic($replyIds)
    {
        $replyIds = array_unique(array_filter($replyIds));
        $str = preg_replace('/(\d+)/', '%s', implode(',', $replyIds));
        $praiseResult = $this->query('SELECT count(*) as PraiseNum,TypeID as ReplyID FROM cms_user_action WHERE (Type = 3 or Type=5) and Flag = 0 AND TypeID in (' . $str . ') group by TypeID', $replyIds);
        $praiseArray = array();
        while ($praiseResult->fetch_assoc()) {
            $praiseArray[$praiseResult->getData('ReplyID')] = $praiseResult->getData('PraiseNum');
        }
        return $praiseArray;
    }

    /*
     * 根据评论ID查询图片
     */
    public function getPictureByCommentID($commentId)
    {
        $comment = $this->query('select TypeID as PictureID from cms_comment where CommentID=%s', array($commentId))->fetch_assoc();
        if(!$comment){
            return array();
        }
        $pictureID = $comment['PictureID'];
        $picture = self::mergeOneDataAndImage(array(), $pictureID);
        unset($picture['CropX'],$picture['CropY'],$picture['CropWidth'],$picture['CropHeight']);
        $picture['FileID'] = $pictureID;
        return $picture;
    }

    public function getCommentType1($commentArray, $orderType)
    {
        $prev = $next = 0;
        if ($orderType == 1) {
            $commentArray[0] = $this->arraySort($commentArray[0], 'CommentID', SORT_DESC);
        }
        if (count($commentArray[0]) > 15) {
            $commentArray[0] = array_splice($commentArray[0], 1, 16);
            $prev = $commentArray[0][0]['CommentID'];
        }
        if (count($commentArray[1]) > 15) {
            $commentArray[1] = array_splice($commentArray, 0, 15);
            $next = $commentArray[1][14]['CommentID'];
        }
        if ($orderType == 1) {
            $commentArray = array_merge($commentArray[0], $commentArray[1]);
        } else {
            $commentArray = array_merge($commentArray[1], $commentArray[0]);
        }
        return array(
            'results' => $this->resolveComment($commentArray),
            'prev' => $prev,
            'next' => $next
        );
    }

    public function getCommentType2($commentArray, $prevCursor, $nextCursor)
    {
        $prev = $next = 0;
        if (count($commentArray) > \haibao\classlibrary\Config::getConfig(\haibao\classlibrary\jiepai\Config::COMMENTS_PAGE_SIZE)) {
            if ($nextCursor) {
                $commentArray = array_splice($commentArray, 0, 30);
                $last = $commentArray[count($commentArray) - 1];
                $next = $last['CommentID'];
                $prev = $nextCursor;
            } elseif ($prevCursor) {
                $commentArray = array_splice($commentArray, 1, 31);
                $next = $prevCursor;
                $first = $commentArray[0];
                $prev = $first['CommentID'];
            } else {
                $commentArray = array_splice($commentArray, 0, 30);
                $last = $commentArray[count($commentArray) - 1];
                $next = $last['CommentID'];
            }
        }

        return array(
            'results' => $this->resolveComment($commentArray),
            'prev' => $prev,
            'next' => $next
        );
    }
    
    public function getContentIdByPictureIds($pictureIds){
    	if(is_array($pictureIds)){
    		$pictureIds = implode(',', $pictureIds);
    	}
    	$result = $this->query('SELECT ContentInfo,max(ID) AS ContentID FROM cms_article_content WHERE ContentInfo in ('.$pictureIds.') GROUP BY ContentInfo');
    	$temp = array();
    	while ($row = $result->fetch_assoc()){
    		$temp[$row['ContentInfo']] = (int)$row['ContentID'];
    	}
    	return $temp;
    }

    public function resolveComment($result)
    {
        $comments = array();
        if ($result) {
            foreach ($result as $key => $item) {
                $temp = array(
                    'CommentID' => $item['CommentID'],
                    'Content' => $item['AuditStatus'] == 1 ? $item['Content'] : $item['Content'],
                    'CreateTime' => $item['CreateTime'],
                    'Scores' => $item['Scores'],
                    'AuditStatus' => $item['AuditStatus'],
                    'SensitiveWords' => $item['SensitiveWords'],
                    'Pictures' => isset($item['Pictures']) ? $item['Pictures'] : '',
                    'IsPraise' => 0,
                    'User' => array(
                        'UserID' => $item['UserID'],
                        'NickName' => $item['NickName'],
                        'Avatar' => isset($item['Avatar']) ? $item['Avatar'] : '',
                    ),
                );
                array_push($comments, $temp);
            }
        }
        return $comments;
    }

    /**
     * 二维数组按照某以键值排序
     * arraySort($array, $keys, $type = SORT_DESC)
     */
    private function arraySort($array, $keys, $type = SORT_DESC)
    {
        $keysValue = $newArray = array();
        foreach ($array as $k => $v) {
            $keysValue[$k] = $v[$keys];
        }
        $type == SORT_ASC ? asort($keysValue) : arsort($keysValue);
        reset($keysValue);
        foreach ($keysValue as $k => $v) {
            array_push($newArray, $array[$k]);
        }
        return $newArray;
    }

}